package com.speedchina.common.message.wechat.message;
import com.alibaba.fastjson.JSON;
import com.speedchina.common.message.wechat.util.Httpclient;
import com.speedchina.framework.utils.JSONUtils;
import lombok.SneakyThrows;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 文件类型
 * @author zyw
 */
public class FileMessage implements  Message {
    static HttpClient httpclient = HttpClients.createDefault();
    List<String> media_idInfos = new ArrayList<String>();

    public void addMdia_id(FileInfo fileInfo){
        media_idInfos.add(fileInfo.getMedia_id());
    }

    /**
     *  指定key发送文件
     * @param key
     * @param file
     */
    @SneakyThrows
    public void getFilemedia_id(String key,MultipartFile file){
        FileInfo fileInfo = new FileInfo();
        String result= Httpclient.httpClientUploadFile("https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key="+key+"&type=file"
                ,Httpclient.multipartFileToFile(file));
        System.out.println(result);
        Map map = JSONUtils.parse(result, Map.class);
        fileInfo.setMedia_id(String.valueOf(map.get("media_id")));
        this.addMdia_id(fileInfo);
    }

    public String toJsonString() {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("msgtype","file");
        Map<String, Object> media_id = new HashMap<String, Object>(50);
        for (int i = 0; i < media_idInfos.size(); i++) {
            media_id.put("media_id",media_idInfos.get(i));
        }
        map.put("file",media_id);
        return JSON.toJSONString(map);
    }
}
